package org.dtrd.modules.record.controller;

import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.aspect.annotation.AutoLog;
import org.dtrd.config.system.Constant;
import org.dtrd.config.system.SystemState;
import org.dtrd.modules.achievement.service.IDtrdEntRdSigninRecordService;
import org.dtrd.modules.record.entity.bean.HeightBean;
import org.dtrd.modules.record.entity.bean.PeriodBmi;
import org.dtrd.modules.record.entity.bean.WeightBmiChartBean;
import org.dtrd.modules.record.entity.request.TimePeriodRequest;
import org.dtrd.modules.record.service.IHeightWeightRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.dtrd.common.constant.CommonConstant.OPERATE_TYPE_QUERY;
import static org.dtrd.common.constant.CommonConstant.OPERATE_TYPE_SAVE_OR_UPDATE;

/**
 * BMI记录
 *
 * @author 萧
 * @date:2021-10-03 19:00:43
 **/
@Slf4j
@RestController
@RequestMapping("/101/06")
@Api(tags = "BMI记录接口")
public class BmiController extends BaseController {

    @Autowired
    private IHeightWeightRecordService heightWeightRecordService;
    @Autowired
    private IDtrdEntRdSigninRecordService signinRecordService;

    @ApiOperation("添加体重记录")
    @PostMapping("/1010605")
    @AutoLog(value="添加体重记录", operateType = OPERATE_TYPE_SAVE_OR_UPDATE)
    public Result<?> saveHeightWeightRecord(@RequestBody HeightBean heightWeightInfo) {
        Integer patientId = heightWeightInfo.getPatientId();
        String recordTime = heightWeightInfo.getTime();
        // 校验 patientId 体重 记录时间
        if (isIntParamInvalid(patientId)
                || heightWeightInfo.getWeight() == null
                || StrUtil.isBlank(recordTime)) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        // 如果保存时没有 height 则查询最近的一条身高进行保存
        if (heightWeightInfo.getHeight() == null) {
            Float height = heightWeightRecordService.getHeightRecordLatest(patientId);
            if (height != null) {
                heightWeightInfo.setHeight(height);
            }
        }
        boolean result = heightWeightRecordService.saveWeight(heightWeightInfo);
        return result ? Result.OK() : error(SystemState.ResponseState.STATE_OPERATION_FAILURE);
    }

    @ApiOperation("根据时段查询BMI")
    @PostMapping("/1010601")
    @AutoLog(value="根据时段查询BMI", operateType = OPERATE_TYPE_QUERY)
    public Result<?> getBmiTimePeriod(@RequestBody TimePeriodRequest request) {
        int patientId = getIntParam(request.getPatientId(), 0);
        if (patientId < 1) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        String startDate = null;
        String endDate = null;
        String[] timePeriod = handleTimePeriod(request);
        if (timePeriod != null) {
            startDate = timePeriod[0];
            endDate = timePeriod[1];
        }
        if (startDate == null || endDate == null) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        PeriodBmi record = heightWeightRecordService.getBmiDataForCharts(patientId, startDate, endDate);
        return Result.OK(record);
    }

    @ApiOperation("BMI记录查询")
    @PostMapping("/1010602")
    @AutoLog(value="BMI记录查询", operateType = OPERATE_TYPE_QUERY)
    public Result<?> getBmiList(@RequestBody TimePeriodRequest request) {
        int patientId = getIntParam(request.getPatientId(), 0);
        if (patientId < 1) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        // 为折线图返回数据 默认0不需要 1 需要
        int forChart = getIntParam(request.getForChart(), 0);
        // 为0表示按日期查询，为1表示按分页查询
        // 3 按照指定周期查询
        int type = getIntParam(request.getType(), 1);
        String startDate = null;
        String endDate = null;
        String[] timePeriod = handleTimePeriod(request);
        if (timePeriod != null) {
            startDate = timePeriod[0];
            endDate = timePeriod[1];
        }
        int page = getIntParam(request.getPage(), 0);
        int pageSize = getIntParam(request.getPageSize(), Constant.PAGESIZE);
        List<HeightBean> list = null;
        WeightBmiChartBean chart = null;
        Integer count = heightWeightRecordService.getHeightWeightRecordCount(patientId, startDate, endDate);
        Map map = new HashMap();
        if (count != null && count > 0) {
            if (type == 0) {
                list = heightWeightRecordService.getAllHeightWeightByUserAndDate(patientId, startDate, endDate);
            } else {
                if (forChart == 1) {
                    chart = heightWeightRecordService.getWeightBmiDataForChartsInApp(patientId, startDate, endDate);
                }
                if (type == 3) {
                    list = heightWeightRecordService.getAllHeightWeightBetweenTimeAndPage(patientId, startDate, endDate, page, pageSize);
                }
            }
            map.put("count", count);
            map.put("totalPage", count <= pageSize || pageSize <= 0 ? 1 : setTotalPage(pageSize, count));
        }else {
            map.put("count", 0);
            map.put("totalPage", 0);
        }
        if (type == 1) {
            list = heightWeightRecordService.getAllHeightWeightByPage(patientId, page, pageSize);
        }

        if (chart == null) {
            map.put("noRecordTips", "暂时还没有记录哦~");
        } else {
            map.put("chart", chart);
        }
        map.put("recordList", list);
        return Result.OK(map);
    }

    @ApiOperation("获取患者身高体重-BMI统计数据")
    @GetMapping(value = "/1010603")
    @AutoLog(value="获取患者身高体重-BMI统计数据", operateType = OPERATE_TYPE_QUERY)
    public Result<?> getBmiStatistics(@RequestParam Integer patientId,
                                                         @RequestParam Integer type, @RequestParam(required = false) String startTime,
                                                         @RequestParam(required = false) String endTime, @RequestParam Integer period) {
        try {
            if (patientId <= 0 || (type != 3 && StringUtils.isEmpty(startTime))) {
                return Result.error(SystemState.ResponseState.STATE_PARAMS_ERROR.getCode(), SystemState.ResponseState.STATE_PARAMS_ERROR.getMsg());
            } else {
                Map map = heightWeightRecordService.getHeightWeightStatistics(patientId, type, startTime, endTime, period);
                return Result.OK(map);
            }
        } catch (Exception e) {
            log.error("获取BMI统计信息异常", e);
            return Result.error(SystemState.ResponseState.STATE_OPERATION_FAILURE.getCode(), SystemState.ResponseState.STATE_OPERATION_FAILURE.getMsg());
        }
    }

}
